<template>
    <div class="qr_code">
      <img :src="dataUrl">
      <canvas ref="canvas" v-show="false"></canvas>
    </div>
</template>
<script>
import qr from 'qr.js'
import api from '../api'
export default {
  props: ['codeurl', 'addSize','logo'],
  data () {
    return {
      dataUrl: '',
      size: 128,
      bgColor: '#fff',
      fgColor: '#000'
    }
  },
  components: {
  },
  mounted () {
    setTimeout(() => {
      this.createQr()
    },10)
  },
  methods: {
    createQr () {
      console.log(this.logo, 80)
      const qrcode = qr(this.codeurl)
      const canvas = this.$refs.canvas
      const ctx = canvas.getContext('2d')
      const size = this.size / qrcode.moduleCount
      const scale = window.devicePixelRatio / this.getPixelRatio(ctx)
      canvas.height = canvas.width = this.size * scale
      ctx.scale(scale, scale)
      qrcode.modules.forEach((row, rdx) => {
        row.forEach((cell, cdx) => {
          ctx.fillStyle = cell ? this.fgColor : this.bgColor
          var w = (Math.ceil((cdx + 1) * size) - Math.floor(cdx * size))
          ctx.fillRect(Math.round(cdx * size), Math.round(rdx * size), w, w)
        })
      })
      var image = document.createElement('img')
      image.src = this.logo
      var sized
      if (this.addSize) {
        sized = 0.15
      } else {
        sized = 0.2
      }
      image.onload = () => {
        var dwidth = this.size * sized
        var dx = (this.size - dwidth) / 2
        var dheight = image.height / image.width * dwidth
        var dy = (this.size - dheight) / 2
        image.width = dwidth
        image.height = dheight
        ctx.drawImage(image, dx, dy, dwidth, dheight)
        this.dataUrl = canvas.toDataURL()
      }
    },
    getPixelRatio (ctx) {
      return ctx.webkitBackingStorePixelRatio || ctx.backingStorePixelRatio || 1
    }
  }
}
</script>
